import { Modal } from 'antd';
import React, { Component } from 'react';
import SlideCaptcha from 'xo-react-slide-captcha/src/index';
import { message } from 'antd';
import SlideStore from '@/stores/get_slider';
import { observer } from 'mobx-react';

interface SliderCaptchaModalProps {
  /**
   * 要发送的手机号
   */
  mobile: string;
  /**
   * 验证码类型 1-手机号注册 2-修改密码获取验证码 3-手机验证码登录
   */
  sendType: number;
  /**
   * modal是否可见
   */
  visible?: boolean;
  /**
   * 发送成功回调
   */
  onSuccess?: () => void;
  /**
   * 对话框关闭
   */
  onCancel?:
    | ((e: React.MouseEvent<HTMLElement, MouseEvent>) => void)
    | undefined;
}

@observer
export default class SliderCaptchaModal extends Component<SliderCaptchaModalProps> {
  store = new SlideStore();

  /**
   * 拖动完成回调
   * @param validateValue
   * @param validatedSuccess
   * @param validatedFail
   * @param resetCaptcha
   */
  resultCallback = async (
    validateValue,
    validatedSuccess,
    validatedFail,
    resetCaptcha,
  ) => {
    const { mobile, sendType, onSuccess } = this.props;
    try {
      const flag = await this.store.sendSms(
        mobile,
        sendType,
        validateValue * 0.9,
      );
      if (flag) {
        validatedSuccess(() => {
          message.success('验证码已成功发送');
          onSuccess?.call(this);
        });
      } else {
        validatedFail(() => {});
      }
    } catch (e) {
      validatedFail(() => {
        message.error('验证失败，请重试');
      });
    }
  };

  /**
   * 刷新滑块点击事件
   */
  handleGetPuzzleInfo = () => {
    this.store.getSliderCaptcha();
  };

  render() {
    const { visible, onCancel } = this.props;

    return (
      <Modal
        footer={null}
        className="slidecapche"
        onCancel={onCancel}
        visible={visible}
        closable={false}
      >
        <SlideCaptcha
          style={{ width: '472px' }}
          displayType="static"
          puzzleUrl={this.store.slideInfo?.captcha?.sliderImage ?? ''}
          bgUrl={this.store.slideInfo?.captcha?.backgroundImage ?? ''}
          onRequest={this.resultCallback}
          onReset={this.handleGetPuzzleInfo}
          containerClassName="test"
          tipsStyle={{ fontSize: '14px' }}
          tipsText="按住滑块，拖住完成下方拼图"
          reset="auto"
          isLoading={this.store.loading}
          resetButton="inline"
          imagePosition="top"
          robotValidate={{
            offsetY: 5,
            handler: () => {
              message.error('验证失败，请重试');
            },
          }}
        />
      </Modal>
    );
  }
}
